package pri.damai.xiaowu.common.log.trace;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import pri.damai.xiaowu.common.core.constant.TraceConstant;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 为
 * @Desc
 * @Author DaMai
 * @Date 2021/5/26 10:40
 * 但行好事，莫问前程。
 */
public class WebTraceFilter extends OncePerRequestFilter {

    public static final String FILTER_NAME = "webTraceFilter";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws IOException, ServletException {
        try {
            String traceId = request.getHeader(TraceConstant.TRACE_ID);
            if (StringUtils.isEmpty(traceId)) {
                ThreadMdcUtil.setTraceId();
            } else {
                ThreadMdcUtil.setTraceId(traceId);
            }
            filterChain.doFilter(request, response);
        } finally {
            ThreadMdcUtil.removeTrace();
        }
    }

}
